package co.za.itweb.brainstormlite;




import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;



public class SingleFeed extends FragmentActivity {

	static String[] titles;
	static String[] images;
	static String[] bigimages;
	static String[] story;
	static String[] published;
	static String[] summary;
	static String[] author;
	String title;
	ListView list;
	LazyAdapter adapter;
	int feedValue;
	int WindowWidth;
	Dialog dialog;
	ProgressDialog progressDialog;
	RSSFeed feed;
    RefreshTask rt;


	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.feedlayout);

		
		
		feedValue = MenuActivity.feedValue;
		

		if (MenuActivity.feedValue == 0) {
			title = "Cover Story";
		}
		if (MenuActivity.feedValue == 1) {
			title = "Upfront";
		}
		if (MenuActivity.feedValue == 2) {
			title = "Indepth";
		}
		if (MenuActivity.feedValue == 3) {
			title = "Features";
		}
		if (MenuActivity.feedValue == 4) {
			title = "Columns";
		}
		if (MenuActivity.feedValue == 5) {
			title = "Lastly";
		}
		if (MenuActivity.feedValue == 6) {
			title = "Editor's note";
		}

		
		
		LinearLayout layout = (LinearLayout) findViewById(R.id.cell2);
		 int colors[] =  {Color.parseColor("#FF1f292f"),Color.parseColor("#FF1f292f")};
			GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,colors);
			layout.setBackgroundDrawable(grad);
			
			
	     TextView titletext=(TextView) findViewById(R.id.title);
	     titletext.setText(title);
		 TextView back=(TextView) findViewById(R.id.cell2).findViewById(R.id.menutext);

	        @SuppressWarnings("unused")
			ImageButton favorites=(ImageButton) findViewById(R.id.cell2).findViewById(R.id.favorites);
	        ImageButton refresh=(ImageButton) findViewById(R.id.cell2).findViewById(R.id.refresh);
	        ImageButton info=(ImageButton) findViewById(R.id.cell2).findViewById(R.id.info);
	        
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent1 = new Intent(SingleFeed.this, MenuActivity.class);
				intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent1);
				finish();
			}
		});
    	   

		
		 
		 refresh.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(SingleFeed.this, Refresh.class);
					startActivityForResult(intent, 1);
					

				
				}
			});
		 
		 
		 info.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(SingleFeed.this, DialogActivity.class);
					startActivity(intent);
					

				
				}
			});
		if (MenuActivity.fList.get(feedValue)==null) {
			Toast.makeText(getApplicationContext(), "Feed is not loaded",
					Toast.LENGTH_LONG).show();
			Intent intent1 = new Intent(SingleFeed.this, MenuActivity.class);
			intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent1);
		} else {
			
			
			titles = new String[MenuActivity.fList.get(feedValue)._itemlist
					.size()];
			images = new String[MenuActivity.fList.get(feedValue)._itemlist
					.size()];
			bigimages = new String[MenuActivity.fList.get(feedValue)._itemlist
					.size()];
			story = new String[MenuActivity.fList.get(feedValue)._itemlist
					.size()];
			published = new String[MenuActivity.fList.get(feedValue)._itemlist
					.size()];
			summary = new String[MenuActivity.fList.get(feedValue)._itemlist
					.size()];
			author = new String[MenuActivity.fList.get(feedValue)._itemlist
					.size()];

			for (int i = 0; i < MenuActivity.fList.get(feedValue)._itemlist
					.size(); i++) {
				if (MenuActivity.fList.get(feedValue)._itemlist.get(i)
						.getTitle() != null) {
					titles[i] = MenuActivity.fList.get(feedValue)._itemlist
							.get(i).getTitle();
				} else {
					titles[i] = "";
				}
				if (MenuActivity.fList.get(feedValue)._itemlist.get(i)
						.getImage() != null) {
					images[i] = MenuActivity.fList.get(feedValue)._itemlist
							.get(i).getImage();
				} else {
					images[i] = "";
				}

				if (MenuActivity.fList.get(feedValue)._itemlist.get(i)
						.getbigImage() != null) {
					bigimages[i] = MenuActivity.fList.get(feedValue)._itemlist
							.get(i).getbigImage();
				} else {
					bigimages[i] = "";
				}
				if (MenuActivity.fList.get(feedValue)._itemlist.get(i)
						.getStory() != null) {
					story[i] = MenuActivity.fList.get(feedValue)._itemlist
							.get(i).getStory().toString();
				} else {
					story[i] = "";
				}
				if (MenuActivity.fList.get(feedValue)._itemlist.get(i)
						.getpubDate() != null) {
					published[i] = MenuActivity.fList.get(feedValue)._itemlist
							.get(i).getpubDate();
				} else {
					published[i] = "";
				}
				if (MenuActivity.fList.get(feedValue)._itemlist.get(i)
						.getSummary() != null) {
					summary[i] = MenuActivity.fList.get(feedValue)._itemlist
							.get(i).getSummary();
				} else {
					summary[i] = "";
				}
				if (MenuActivity.fList.get(feedValue)._itemlist.get(i)
						.getAuthor() != null) {
					author[i] = MenuActivity.fList.get(feedValue)._itemlist
							.get(i).getAuthor();
				} else {
					author[i] = "";
				}
			}

			list = (ListView) findViewById(R.id.list);
			adapter = new LazyAdapter(this, images);
			list.setAdapter(adapter);
			list.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent intent = new Intent(SingleFeed.this,
							SingleNews.class);
					intent.putExtra("id", position);
					intent.putExtra("feedid", feedValue);
					startActivity(intent);
				}
			});

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 1) {

			if (resultCode == RESULT_OK) {
				adapter.notifyDataSetChanged();
				Toast.makeText(getApplicationContext(),
						"News are refreshed...", Toast.LENGTH_SHORT).show();
			}

			if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(),
						"There was mistake while refreshing...", Toast.LENGTH_SHORT).show();
				

			}
		}
	}
	
	

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent1 = new Intent(SingleFeed.this, MenuActivity.class);
			intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent1);
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
	
		Intent intent1 = new Intent(SingleFeed.this, MenuActivity.class);
		intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent1);
		this.finish();
		return ;
		
	}
	
	public class RefreshTask extends AsyncTask<Void, Integer, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			if (isCancelled()){
				
				return null;
				
				}
			MenuActivity.fList.clear();
			for (int o = 0; o < MenuActivity.feeds.length; o++) {
				feed = getFeed(MenuActivity.feeds[o]);

				if (feed != null) {
					MenuActivity.fList.add(feed);

				}
			}

			return null;
		}

		protected void onPreExecute() {
			
		}

		@Override
		protected void onPostExecute(Void result) {
			if(progressDialog.isShowing()){
			progressDialog.dismiss();
			}
			Intent returnIntent = new Intent();
			setResult(RESULT_CANCELED, returnIntent);
			finish();

		}
	}
	
	public static RSSFeed getFeed(String urlToRssFeed) {
		try {

			URL url = new URL(urlToRssFeed);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);

			SAXParser parser = factory.newSAXParser();

			XMLReader xmlreader = parser.getXMLReader();

			RSSHandler theRssHandler = new RSSHandler();

			xmlreader.setContentHandler(theRssHandler);

			InputSource is = new InputSource(url.openStream());

			xmlreader.parse(is);

			System.out.println("FFFFFFFEEEEEEEEEEEDDDDDDDDDDDDDDDDD"
					+ theRssHandler.getFeed());
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
					+ ee.toString());
			return null;
		}
	}

}
